local skynet = require "skynet"
local socket = require "skynet.socket"
local netpack = require "skynet.netpack"
local cjson   = require "cjson"
local msgpack = require "msgpack"
local config  = require "config"
local WATCHDOG
local host
local send_request

local CMD = {}
local REQUEST = {}
local client_fd


local function send_package(pack)
    if not client_fd then
        return
    end
    local data = pack.data
    if data and data.errcode and data.errcode>0 and not data.errmsg then
        data.errmsg = config.get("errmsg",string.format("e%d",data.errcode))
    end
    skynet.error("agent send",pack.c,pack.m)
    socket.write(client_fd,netpack.pack(cjson.encode(pack)))
end

function REQUEST:quit()
    skynet.call(WATCHDOG, "lua", "close", client_fd)
end

local function request(name, args, response)
    local f = assert(REQUEST[name])
    local r = f(args)
    if response then
        return response(r)
    end
end

function REQUEST.on_room_sendmsg(cmd)
    skynet.error("on_room_sendmsg cmd = ",cjson.encode(cmd))
    local data = cmd.data
    local roomid = data.roomid
    local msg_type = data.msg_type
    local msg = data.msg
    if roomid and msg_type and msg then
        local ok = pcall(skynet.call,"roommgr","lua", "sendmsg", roomid, msg_type, msg)
    end
end


skynet.register_protocol {
    name = "client",
    id = skynet.PTYPE_CLIENT,
    unpack = function (msg, sz)
        local a= skynet.tostring(msg,sz)
        -- return funpack(a)
        return a
    end,
    dispatch = function (fd, _, data)
        skynet.ignoreret()
        -- skynet.error('接收到新的消息了==============>>>>>>>>>>>>>', fd,data)
        local ok, cmd = pcall(msgpack.decode, data)
        skynet.error("inner agent recv msg ===>", cjson.encode(cmd))
        if ok then
            local c = cmd.c
            local m = cmd.m
            local fname = string.format("on_%s_%s",c,m)

            local f  = REQUEST[fname]
            if f then
                local result = f(cmd)
                if result then
                    -- skynet.error("sesssion:"..session)
                    send_package(result)
                end
            end
        end
    end
}

function CMD.start(conf)
    local fd = conf.client
    local gate = conf.gate
    WATCHDOG = conf.watchdog
    client_fd = fd
    skynet.call(gate, "lua", "forward", fd)
    skynet.error("inner agent forward")
end

function CMD.disconnect()
    skynet.exit()
end

skynet.start(function()
    skynet.dispatch("lua", function(_,_, command, ...)
        -- skynet.trace()
        local f = CMD[command]
        skynet.ret(skynet.pack(f(...)))
    end)
end)
